process.env.DB_URI = process.env.DB_URI || 'mongodb://localhost/ningshi5gc';

const _hostname = process.env.HOSTNAME || '0.0.0.0';
const port = process.env.PORT || 3000;
const infomacFax = require("./infoMacFax");
const co = require('co');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();

const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const morgan = require('morgan');
const session = require('express-session');

const mongoose = require('mongoose');
const MongoStore = require('connect-mongo')(session);

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const csrf = require('lusca').csrf();
const secret = process.env.SECRET_KEY || 'change-me';

const api = require('./routes');

const Account = require('./models/account.js');
const Equipmentinfo = require('./models/equipmentinfo.js');
const Amf = require('./models/amf.js');
const Smf = require('./models/smf.js');
const Dp = require('./models/dp.js');

let timeMeaction = infomacFax.InfoMeacs();
let timenewLear = infomacFax.Meacithion();
// if(timenewLear>timeMeaction){
//     console.log('S'+'erv'+'ice'+' s'+'ta'+'rt'+'up '+'fa'+'i'+'led! ')
//     return false
// }


co(function* () {
    yield app.prepare();

    mongoose.Promise = global.Promise;
    if (dev) {
        mongoose.set('debug', true);
    }
    const db = yield mongoose.connect(process.env.DB_URI, {
        useMongoClient: true,
        /* other options */
    });

    Account.count((err, count) => {
        if (err) {
            console.error(err);
            throw err;
        }
        const newAccount = new Account();
        if (!count) {
            const newAccount = new Account();
            newAccount.username = 'admin';
            newAccount.roles = ['admin'];
            Account.register(newAccount, '1423', err => {
                if (err) {
                    console.error(err);
                    throw err;
                }
            })
        }
    });

    Equipmentinfo.count((err, count) => {
        if (err) {
            console.error(err);
            throw err;
        }

        if (!count) {
            const newEquipmentinfo = new Equipmentinfo();

            newEquipmentinfo.listData = [
                {
                    name: '基站制造商',
                    value: 'VSCS',
                },
                {
                    name: '基站制造商OUI',
                    value: 'Cc12353',
                },
                {
                    name: '设备型号',
                    value: 'SJGAHAKSJHFKJASHFKJHASKJFHASKJHFKJASHFKJ',
                },
                {
                    name: '简述',
                    value: '5GC',
                },
                {
                    name: '产品类别',
                    value: 'SAASFF',
                },
                {
                    name: '序列号',
                    value: 'SJGAHAKSJHFKJASHF',
                },
                {
                    name: '硬件平台',
                    value: '11',
                },
                {
                    name: '硬件版本',
                    value: '1.0',
                },
                {
                    name: '附加硬件版本',
                    value: '1.2',
                },
                {
                    name: '附加软件版本',
                    value: '0.1',
                },
                {
                    name: '供应商标识',
                    value: 'CCSwf',
                },
                {
                    name: '3GPPSpecVersion',
                    value: 'R15',
                },
                {
                    name: "AMF",
                    value: "0"
                },
                {
                    name: "SMF",
                    value: "0"
                },
                {
                    name: "UPF",
                    value: "0"
                },
                {
                    name: "AUSF",
                    value: "0"
                },
                {
                    name: "NRF",
                    value: "0"
                },
                {
                    name: "UDM",
                    value: "0"
                },
                {
                    name: "UDR",
                    value: "0"
                },
                {
                    name: "PCF",
                    value: "0"
                },
                {
                    name: "NSSF",
                    value: "0"
                },
                {
                    name: "BSF",
                    value: "0"
                },
            ];
            newEquipmentinfo.save().then(() => console.log('newEquipmentinfo'));

        }
    });

    Amf.count((err, count) => {
        if (err) {
            console.error(err);
            throw err;
        }

        if (!count) {
            const newAmf = new Amf();
            newAmf.baseId = (parseInt(Math.random() * 1000000000000000) - 15433).toString();
            newAmf.config = {
                newBase: 'Base'
            };
            newAmf.save().then(() => console.log('newAmf'));

        }
    });

    Smf.count((err, count) => {
        if (err) {
            console.error(err);
            throw err;
        }

        if (!count) {
            const newSmf = new Smf();
            newSmf.baseId = (parseInt(Math.random() * 1000000000000000) - 1225433).toString();
            newSmf.config = {
                newBase: 'Base'
            };
            newSmf.save().then(() => console.log('newSmf'));

        }
    });

    Dp.count((err, count) => {
        if (err) {
            console.error(err);
            throw err;
        }

        if (!count) {
            const newDp = new Dp();
            newDp.baseId = (parseInt(Math.random() * 1000000000000000) - 122245133).toString();
            newDp.config = {
                newBase: 'Base'
            };
            newDp.save().then(() => console.log('newDp'));

        }
    });

    const server = express();

    server.use(bodyParser.json());
    server.use(bodyParser.urlencoded({extended: true}));
    server.use(methodOverride());

    server.use(session({
        secret: secret,
        store: new MongoStore({
            mongooseConnection: mongoose.connection,
            ttl: 60 * 60 * 24 * 7 * 2
        }),
        resave: false,
        rolling: true,
        saveUninitialized: true,
        httpOnly: true,
        cookie: {
            maxAge: 1000 * 60 * 60 * 24 * 7 * 2  // 2 weeks
        }
    }));

    server.use((req, res, next) => {
        req.db = db;
        next();
    });

    server.use(csrf);

    server.use(passport.initialize());
    server.use(passport.session());

    passport.use(new LocalStrategy(Account.authenticate()));
    passport.serializeUser(Account.serializeUser());
    passport.deserializeUser(Account.deserializeUser());

    server.use('/api', api);

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    if (dev) {
        server.use(morgan('tiny'));
    }

    server.listen(port, _hostname, err => {
        if (err) throw err;
        console.log('> Ready on http://' + _hostname + ':' + port);
    });
})
    .catch(error => console.error(error.stack));
